package com.bocloud.cmp.service.resource;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.dao.CloudVendorDao;
import com.bocloud.cmp.dao.RegionDao;
import com.bocloud.cmp.dao.SecurityGroupDao;
import com.bocloud.cmp.driver.providers.intf.SecurityGroupProvider;
import com.bocloud.cmp.entity.resource.CloudVendor;
import com.bocloud.cmp.entity.resource.Region;
import com.bocloud.cmp.entity.resource.SecurityGroup;
import com.bocloud.cmp.interfaces.resource.SecurityGroupService;
import com.bocloud.cmp.model.SecurityGroupBean;
import com.bocloud.cmp.model.SecurityGroupModel;
import com.bocloud.common.model.BsmResult;
import com.bocloud.common.model.GridBean;
import com.bocloud.common.model.Param;
import com.bocloud.common.model.SimpleBean;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.MapTools;
import com.bocloud.coordinator.harmony.HarmonyLock;
import com.bocloud.coordinator.harmony.LockFactory;
import com.google.common.collect.Maps;

/**
 * 安全组Service接口实现
 * 
 * @author dongkai
 *
 */
@Service("securityGroupService")
public class SecurityGroupServiceImpl implements SecurityGroupService {

	private static Logger logger = LoggerFactory.getLogger(ImageServiceImpl.class);
	@Autowired
	private LockFactory lockFactory;
	@Autowired
	private SecurityGroupDao sGroupDao;
	@Autowired
	private RegionDao regionDao;
	@Autowired
	private CloudVendorDao cloudVendorDao;
	@Autowired
	private SecurityGroupProvider securityGroupProvider;

	@Override
	public BsmResult list(int page, int rows, List<Param> params, Map<String, String> sorter, Boolean simple) {
		List<SecurityGroup> list = null;
		List<SimpleBean> beans = null;
		int total = 0;
		GridBean gridBean = null;
		try {
			if (null == params) {
				params = new ArrayList<>();
			}
			if (null == sorter) {
				sorter = Maps.newHashMap();
			}
			sorter.put("gmtCreate", Common.ONE);
			total = sGroupDao.count(params);
			if (simple) {
				beans = sGroupDao.list(params, sorter);
				gridBean = new GridBean(1, 1, total, beans);
			} else {
				list = sGroupDao.list(page, rows, params, sorter);
				for (SecurityGroup securityGroup : list) {
					Region region = regionDao.query(securityGroup.getRegion());
					if (null != region) {
						securityGroup.setRegionName(region.getName());
					}
				}
				gridBean = GridHelper.getBean(page, rows, total, list);
			}
			return new BsmResult(true, gridBean, "查询成功");
		} catch (Exception e) {
			logger.error("Query SecurityGroup list fail:", e);
			return new BsmResult(false, "查询失败", null, null);
		}
	}

	@Override
	public BsmResult remove(Long id) {
		String path = SecurityGroup.class.getSimpleName() + "_" + id;
		HarmonyLock lock = null;
		Boolean result = false;
		try {
			lock = lockFactory.getLock(path);
			if (!lock.acquire(path, 10, TimeUnit.SECONDS)) {
				logger.warn("Get harmonyLock time out!");
				return new BsmResult(false, "请求超时", "", "");
			}
			SecurityGroup sgroup = sGroupDao.query(id);
			if (null == sgroup) {
				logger.warn("SecurityGroup data not exist");
				return new BsmResult(false, "数据不存在", "", "");
			}

			CloudVendor cloudVendor = cloudVendorDao.query(sgroup.getVendorId());
			Region reg = regionDao.query(sgroup.getRegion());
			if (null == cloudVendor) {
				logger.error("get cloudVendor and reg failure!");
				return new BsmResult(false, "同步失败!");
			}
			BsmResult bsmResult = securityGroupProvider.remove(sgroup.getUuid(), cloudVendor.getUuid(), reg.getCode());
			if (null == bsmResult || !bsmResult.isSuccess()) {
				return new BsmResult(false, "删除失败!");
			}
			result = sGroupDao.delete(id);
		} catch (Exception e) {
			logger.error("remove failure:", e);
			return new BsmResult(false, "删除失败!");
		} finally {
			if (null != lock) {
				lock.release();
			}
		}
		return result ? new BsmResult(true, "删除成功") : new BsmResult(false, "删除失败!", "", "");
	}

	@Override
	public BsmResult sync(Long id, Long region) {
		try {
			CloudVendor cloudVendor = cloudVendorDao.query(id);
			Region reg = regionDao.query(region);
			if (null == cloudVendor || null == reg) {
				logger.error("get cloudVendor and reg failure!");
				return new BsmResult(false, "同步失败!");
			}
			// 启动一个线程从MQ上获取数据
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						BsmResult bsmResult = securityGroupProvider.list(cloudVendor.getUuid(), reg.getCode());
						if (null != bsmResult.getData()) {
							String content = JSONObject.toJSONString(bsmResult.getData());
							JSONArray result = JSONArray.parseArray(content);
							List<SecurityGroup> sgroups = sGroupDao.listByVendorId(id);
							List<SecurityGroup> resultData = new ArrayList<>();
							resultData.addAll(sgroups);
							for (Object obj : result) {
								boolean flag = true;
								SecurityGroupBean bean = JSONObject.parseObject(obj.toString(),
										SecurityGroupBean.class);
								for (SecurityGroup sgroup : sgroups) {
									if (bean.getUuid().equals(sgroup.getUuid())) {
										flag = false;
										BeanUtils.copyProperties(bean, sgroup);
										sGroupDao.modify(sgroup);
										resultData.remove(sgroup);
									}
								}
								if (flag) {
									SecurityGroup sgroup = JSONObject.parseObject(obj.toString(), SecurityGroup.class);
									sgroup.setRegion(region);
									sgroup.setVendorId(id);
									sgroup.setGmtCreate(new Date());
									sGroupDao.save(sgroup);
								}
							}
							// 删除异常数据
							for (SecurityGroup sGroup : resultData) {
								sGroupDao.delete(sGroup.getId());
							}
						}
					} catch (Exception e) {
						logger.error("Get Message Exception:", e);
					}
				}
			}).start();
			return new BsmResult(true, "同步任务已经下发，正在执行……");
		} catch (Exception e) {
			logger.error("sync failure:", e);
			return new BsmResult(false, "同步失败!");
		}
	}

	@Override
	public BsmResult detail(Long id) {
		try {
			SecurityGroup sgroup = sGroupDao.query(id);
			Region region = regionDao.query(sgroup.getRegion());
			if (null != region) {
				sgroup.setRegionName(region.getName());
			}
			return new BsmResult(true, sgroup, "查询成功！");
		} catch (Exception e) {
			logger.error("get detail failure:", e);
			return new BsmResult(false, "查询失败!");
		}
	}

	@Override
	public BsmResult create(String name, String remark, Long id, Long region) {
		try {
			CloudVendor cloudVendor = cloudVendorDao.query(id);
			Region reg = regionDao.query(region);
			if (null == cloudVendor) {
				logger.error("get cloudVendor and reg failure!");
				return new BsmResult(false, "创建失败!");
			}
			Map<String, Object> param = MapTools.simpleMap("name", name);
			param.put("remark", remark);
			SecurityGroupModel model = JSONObject.parseObject(JSONObject.toJSONString(param), SecurityGroupModel.class);
			BsmResult bsmResult = securityGroupProvider.create(cloudVendor.getUuid(), reg.getCode(), model);
			if (null == bsmResult || !bsmResult.isSuccess()) {
				return new BsmResult(false, "创建失败!");
			}
			SecurityGroup sgroup = JSONObject.parseObject(bsmResult.getData().toString(), SecurityGroup.class);
			sgroup.setRegion(region);
			sgroup.setVendorId(id);
			sGroupDao.save(sgroup);
			return new BsmResult(true, "创建成功!");
		} catch (Exception e) {
			logger.error("create failure:", e);
			return new BsmResult(false, "创建失败!");
		}
	}

}
